<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="宠物名称" prop="petName">
        <el-input v-model="queryParams.petName" placeholder="请输入宠物名称" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="发布人" prop="publisherName">
        <el-input v-model="queryParams.publisherName" placeholder="请输入发布人" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="发布状态" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">发布申请</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['pet:publish:remove']">
          删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="publishList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="发布编号" align="center" prop="publishId"/>
      <el-table-column label="宠物名称" align="center" prop="petName"/>
      <el-table-column label="发布人" align="center" prop="publisherName"/>
      <el-table-column label="联系电话" align="center" prop="phone"/>
      <el-table-column label="宠物类型" align="center" prop="petTypeName"/>
      <el-table-column label="宠物性别" align="center" prop="gender">
        <template slot-scope="scope">
          <span>{{ getGenderLabel(scope.row.gender) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="宠物年龄" align="center" prop="age"/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ getStatusLabel(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="publishTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.publishTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="approveBy"/>
      <el-table-column label="审核时间" align="center" prop="approveTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approveTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核意见" align="center" prop="comment" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)" v-hasPermi="['pet:publish:query']">
            查看
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['pet:publish:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList"/>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="宠物名称" prop="petName">
              <el-input v-model="form.petName" placeholder="请输入宠物名称" :disabled="!isAdd"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" :disabled="!isAdd"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宠物类型" prop="petType">
              <el-select v-model="form.petType" placeholder="请选择宠物类型" :disabled="!isAdd" @change="handlePetTypeChange">
                <el-option
                  v-for="dict in petTypeOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宠物性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择宠物性别">
                <el-option v-for="dict in genderOptions" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宠物年龄" prop="age">
              <el-input-number v-model="form.age" :min="0" :max="100" label="宠物年龄"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="宠物描述" prop="description">
              <el-input type="textarea" v-model="form.description" placeholder="请输入宠物描述"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="宠物图片" prop="image">
              <el-upload
                class="avatar-uploader"
                :action="uploadImgUrl"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="isAdd" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">{{ isAdd ? '取 消' : '关 闭' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPublish, getPublish, delPublish, addPublish } from "@/api/user/publish";
import { listCategory } from "@/api/pet/category";
import {getToken} from "@/utils/auth";

export default {
  name: "PetPublish",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 宠物发布列表
      publishList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        petName: null,
        publisherName: null,
        status: null
      },
      // 表单参数
      form: {},
      // 状态选项
      statusOptions: [
        { value: "0", label: "待审核" },
        { value: "1", label: "已通过" },
        { value: "2", label: "已拒绝" }
      ],
      // 性别选项
      genderOptions: [
        { value: "0", label: "公" },
        { value: "1", label: "母" }
      ],
      // 表单校验
      rules: {
        petName: [
          { required: true, message: "宠物名称不能为空", trigger: "blur" }
        ],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        petType: [
          { required: true, message: "宠物类型不能为空", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "宠物性别不能为空", trigger: "change" }
        ],
        age: [
          { required: true, message: "宠物年龄不能为空", trigger: "blur" }
        ],
        description: [
          { required: true, message: "宠物描述不能为空", trigger: "blur" }
        ]
      },
      // 上传图片URL
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 图片URL
      imageUrl: "",
      // 宠物类型选项
      petTypeOptions: [],
      // 是否为新增
      isAdd: true,
      headers: { Authorization: "Bearer " + getToken() }
    };
  },
  created() {
    this.getList();
    this.getPetTypes();
  },
  methods: {
    /** 查询发布列表 */
    getList() {
      this.loading = true;
      listPublish(this.queryParams).then(response => {
        this.publishList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询宠物类型 */
    getPetTypes() {
      listCategory().then(response => {
        this.petTypeOptions = response.rows.map(item => {
          return {
            value: item.categoryId,
            label: item.categoryName
          };
        });
      });
    },
    /** 处理宠物类型选择变化 */
    handlePetTypeChange(value) {
      const selectedType = this.petTypeOptions.find(item => item.value === value);
      if (selectedType) {
        this.form.petTypeName = selectedType.label;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.publishId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const publishId = row.publishId || this.ids;
      getPublish(publishId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看发布信息";
        this.isAdd = false;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const publishIds = row.publishId || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + publishIds + '"的发布信息？').then(() => {
        return delPublish(publishIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 获取状态标签 */
    getStatusLabel(status) {
      const found = this.statusOptions.find(option => option.value === status);
      return found ? found.label : '';
    },
    /** 获取性别标签 */
    getGenderLabel(gender) {
      const found = this.genderOptions.find(option => option.value === gender);
      return found ? found.label : '';
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "发布宠物";
      this.isAdd = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.image = this.imageUrl; // 保存图片URL
          addPublish(this.form).then(response => {
            this.$modal.msgSuccess("发布成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    // 图片上传成功处理
    handleImageSuccess(res, file) {
      if (res.code === 200) {
        this.imageUrl = res.url;
        this.$modal.msgSuccess("上传成功");
      } else {
        this.$modal.msgError("上传失败");
      }
    },
    // 上传前图片格式校验
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    }
  }
};
</script>

<style scoped>
.el-table .el-table__header-wrapper th {
  word-break: break-word;
  background-color: #f8f8f9;
  color: #515a6e;
  height: 40px;
  font-size: 13px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
